package com.atgulimall.com.cart.intercept;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponseVo;
import com.atgulimall.com.cart.config.RedisEx;
import com.atgulimall.com.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 满超
 * @date 2020/06/20
 * 拦截器，在执行目标方法之前判断用户状态，并封装传递给目标
 **/
@Component
public class CartInterceptor implements HandlerInterceptor {

    //同线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    //目标执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        //读取登录用户
        MemberResponseVo attribute = (MemberResponseVo) request.getSession().getAttribute(RedisEx.LOGIN_USER);
        if (attribute != null){
            //登录了，获取登录购物车
            userInfoTo.setUserId(attribute.getId());
        }
        
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //user-key有没有
                String name = cookie.getName();
                if (name.equals(CartConstant.TEAM_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(name);
                    userInfoTo.setTempUser(true);
                }
            }
        }
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            //没临时用户，自己设置一个
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }
        threadLocal.set(userInfoTo);
        //放行
        return true;
    }

    //业务执行之后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.getTempUser()){
            //持续延长临时用户保存时间
            //设置cookie
            Cookie cookie = new Cookie(CartConstant.TEAM_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");//作用域
            cookie.setMaxAge(CartConstant.TEAM_USER_COOKIE_TimeOut);
            response.addCookie(cookie);
        }
    }
}
